package com.it2297.view;

import java.awt.BorderLayout;
import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.ArrayList;

import javax.swing.DefaultComboBoxModel;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JSeparator;
import javax.swing.JTable;
import javax.swing.JToolBar;
import javax.swing.ListSelectionModel;
import javax.swing.table.DefaultTableModel;

import com.it2297.component.AbstractPagination;
import com.it2297.controller.JobController;
import com.it2297.controller.ProductController;
import com.it2297.controller.UsedItemController;
import com.it2297.main.CompanyApp;
import com.it2297.main.UserApp;
import com.it2297.model.Job;
import com.it2297.model.Product;
import com.it2297.renderer.ApplicationCellRenderer;
import com.it2297.renderer.JobApplicantsCellRenderer;
import com.it2297.renderer.ProductCellRenderer;
import javax.swing.JLabel;
import java.awt.Component;
import javax.swing.Box;
import java.awt.Font;
import java.awt.Color;
import javax.swing.SwingConstants;

public class ManageJobApplicants extends JFrame {

	final JobController jct= new JobController(this);

	private JMenuBar menuBar;
	private JMenu menuHome;
	private JMenu menuExit;
	private JMenu menuJobAd;
	private JMenuItem menuRemoveJob;
	private JMenuItem menuCreateJob;
	private JMenuItem menuViewAllJobsByCompany;
	private JMenu menuApplicants;
	private JMenuItem menuViewApplicants;
	private JSeparator separator;
	private Component horizontalGlue;
	private Component horizontalStrut;
	private JLabel lblWelcome;
	private JMenuItem menuLogout;
	private JMenuItem menuhomescreen;
	private JMenu mnProfile;
    private JMenuItem mntmUpdateCompany;
	
	private final JTable table = new JTable();
	private final DefaultTableModel tableModel = new DefaultTableModel(0, 2) {
		@Override
		public boolean isCellEditable(int row, int column) {
			return false;
		}
	};
	private final JobApplicantsCellRenderer tableCellRenderer = new JobApplicantsCellRenderer();
	//private final AbstractPagination pagination = new ViewPagination();
	private final JToolBar toolBar = new JToolBar();
	private final Job job = new Job();
	private JComboBox cb_title;
	private String title;
	private JLabel lbl;
	private Component horizontalGlue_1;
	private JLabel lblNewLabel;
	private JButton btnShortlistApplicants;
	
/*	
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					ManageJobApplicants frame = new ManageJobApplicants();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}
	*/
	public ManageJobApplicants() {
		initGUI();
	}

	
	
	private void initGUI() {
		this.setBounds(100, 100, 740, 560);
		getContentPane().setLayout(null);
		table.setBounds(0, 68, 724, 454);
		getContentPane().add(table);
	//	getContentPane().add(pagination, BorderLayout.SOUTH);
		String currentWorkingDirectory = System.getProperty("user.dir");

		table.setRowHeight(100);
		table.setShowGrid(false);
		table.setFocusable(false);
		table.setModel(tableModel);

		table.getColumnModel().getColumn(0).setMaxWidth(60);
		table.getColumnModel().getColumn(1).setMaxWidth(700);
		table.getColumnModel().getColumn(0).setCellRenderer(tableCellRenderer);
		table.getColumnModel().getColumn(1).setCellRenderer(tableCellRenderer);
		
		
		table.addMouseListener(new MouseAdapter() {
			public void mouseClicked(MouseEvent mouseEvent) {
				if (mouseEvent.getClickCount() > 1) {
				//	comView.refresh();
				//	controller.showProductDetail();
				//	JOptionPane.showMessageDialog(null, "Testing");
				}
			}
		});
	/*	toolBar.setBounds(0, 0, 724, 26);
		toolBar.setBackground(Color.GRAY);
		toolBar.setFloatable(false);

		getContentPane().add(toolBar);
		*/
		JButton btnRefresh = new JButton("Refresh");
		btnRefresh.setFont(new Font("Tahoma", Font.BOLD, 15));
		toolBar.add(btnRefresh);
		
		
		
		
		
		cb_title = new JComboBox();
		cb_title.addItem("--------------Select a job advertisement--------------");
		cb_title.revalidate();
		for(int i=0; i<jct.getAllJobsByCompany().size();i++){
            cb_title.addItem(jct.getAllJobsByCompany().get(i));
            }
		cb_title.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				AbstractPagination pagination = new ViewPagination();
				pagination.refresh();
				table.setVisible(true);
				btnShortlistApplicants.setEnabled(true);
				
				 if(cb_title.getSelectedItem()==("--------------Select a job advertisement--------------")){
					 pagination.refresh();
					 table.setVisible(false);
					 lbl.setText("");
					 btnShortlistApplicants.setEnabled(false);
				 }
				 else if(jct.getTotalNumOfApplicantsOfJob()==0){
					//	JOptionPane.showMessageDialog(null, "You do not have anymore pending applications!");
						table.setVisible(false);
						lbl.setText("<html>There are no pending applications for the </br>'" + cb_title.getSelectedItem().toString() + "' job.</html>");
						btnShortlistApplicants.setEnabled(false);
					}
			}
		});
		
		cb_title.setBounds(0, 45, 288, 23);
		getContentPane().add(cb_title);
		
		
		lbl = new JLabel("");
		lbl.setBackground(new Color(255, 255, 255));
		lbl.setVerticalAlignment(SwingConstants.TOP);
		lbl.setHorizontalAlignment(SwingConstants.CENTER);
		lbl.setFont(new Font("Tahoma", Font.BOLD, 17));
		lbl.setBounds(0, 83, 724, 439);
		getContentPane().add(lbl);
		
		JToolBar toolBar_1 = new JToolBar();
		toolBar_1.setBounds(0, 22, 724, 23);
		getContentPane().add(toolBar_1);
		
		lblNewLabel = new JLabel("");
		lblNewLabel.setForeground(new Color(139, 0, 0));
		lblNewLabel.setFont(new Font("Times New Roman", Font.BOLD, 15));
		toolBar_1.add(lblNewLabel);
		
		horizontalGlue_1 = Box.createHorizontalGlue();
		toolBar_1.add(horizontalGlue_1);
		
		btnShortlistApplicants = new JButton("Shortlist Applicant(s)");
		btnShortlistApplicants.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				
				
				
				/*
				 * if(cb_applicants.getSelectedItem()=="------------------Select an applicant--------------"){
					JOptionPane.showMessageDialog(null, "Please select an applicant!");
				}
				else{
					int option = JOptionPane.showConfirmDialog (null, "Are you sure you want to shortlist this applicant?",null, JOptionPane.YES_NO_OPTION);
					if (option == JOptionPane.YES_OPTION ) {
						
						jct.shortlistApplicant();
						JOptionPane.showMessageDialog(null, "Applicant shortlisted! Send an email to notify the applicant.");
						cb_applicants.removeItem(cb_applicants.getSelectedItem().toString());
						int count = cb_applicants.getItemCount()-1;
						lblApplicants.setText("Showing " + count + " applicant(s): ");
						cb_applicants.setSelectedItem("------------------Select an applicant--------------");
							if(cb_applicants.getItemCount()==1){
								JOptionPane.showMessageDialog(null, "There are currently no other pending applications for this job!");
								closeWindow();
							}
							
						CompanySendEmail cse = new CompanySendEmail();
						cse.setLocationRelativeTo(null);
						cse.setVisible(true);
					}
					else {
						JOptionPane.showMessageDialog(null, "Cancelled.");
					}
				}
				 */
				boolean isSuccessful =  jct.shortlistApplicants();
				int option = JOptionPane.showConfirmDialog (null, "Are you sure you want to shortlist the selected applicant(s)?",null, JOptionPane.YES_NO_OPTION);
				if (option == JOptionPane.YES_OPTION ) {
					
					
							if(isSuccessful){	
								JOptionPane.showMessageDialog(null, "Applicant shortlisted! Send an email to notify the applicant.");
								CompanySendEmail cse = new CompanySendEmail();
								String subject = "Removal";
								cse.setSubject(subject);
								String message = "I would like to remove my application to this job as I have already found a job.";
								cse.setMessage(message);
								cse.setVisible(true);
								cse.setTitle("Send Email");
								
								
								if(jct.getTotalNumOfApplicantsOfJob()==0){
									lbl.setText("<html>There are no pending applications for the </br>'" + cb_title.getSelectedItem().toString() + "' job.</html>");
									table.setVisible(false);
									btnShortlistApplicants.setEnabled(false);
								}
							}
							else if (!isSuccessful){
								JOptionPane.showMessageDialog(null, "Please select an applicant first!");
							}
							AbstractPagination pagination = new ViewPagination();
							pagination.setTotal(jct.getTotalNumOfApplicantsOfJob());
							pagination.refresh();
				}
				else{
					
				}
			}
		});
		btnShortlistApplicants.setFont(new Font("Times New Roman", Font.BOLD, 13));
		toolBar_1.add(btnShortlistApplicants);
		
		
		
		
		
		menuBar = new JMenuBar();
		menuBar.setBounds(0, 0, 724, 24);
		getContentPane().add(menuBar);
		
		menuHome = new JMenu("Home");
		menuBar.add(menuHome);
		menuhomescreen=new JMenuItem("Home Screen");
		menuhomescreen.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				CompanyHomePage chp=new CompanyHomePage();
				chp.setLocationRelativeTo(null);
				chp.setVisible(true);
				chp.setTimer("start");
				chp.setTitle("Company - Home Screen");
				closeWindow();
			}
		});
		menuHome.add(menuhomescreen);
		
		menuJobAd=new JMenu("Job Advertisement");
		menuBar.add(menuJobAd);
		menuCreateJob=new JMenuItem("Create Job Advertisement");
		menuCreateJob.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				JobCreateJob jcj=new JobCreateJob();
				jcj.setLocationRelativeTo(null);
				jcj.setVisible(true);
				jcj.setTitle("Company - Create Job Advertisement ");
				closeWindow();
			}
		});
		menuJobAd.add(menuCreateJob);
		
		JSeparator separator_1 = new JSeparator();
		menuJobAd.add(separator_1);
		menuRemoveJob=new JMenuItem("Remove Job Advertisement");
		menuRemoveJob.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				JobRemoveJob jrj=new JobRemoveJob();
				jrj.setLocationRelativeTo(null);
				jrj.setVisible(true);
				jrj.setTitle("Company - Remove Job Advertisement ");
				closeWindow();
			}
		});
		menuViewAllJobsByCompany=new JMenuItem("View All Jobs By Company");
		menuViewAllJobsByCompany.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				CompanyViewAllJobsByCompany cvajbc=new CompanyViewAllJobsByCompany();
				cvajbc.setLocationRelativeTo(null);
				cvajbc.setVisible(true);
				cvajbc.setTitle("Company - View All Jobs By Company ");
				closeWindow();
			}
		});
		menuJobAd.add(menuViewAllJobsByCompany);
		
		JSeparator separator_2 = new JSeparator();
		menuJobAd.add(separator_2);
		menuJobAd.add(menuRemoveJob);
		
		horizontalGlue = Box.createHorizontalGlue();
		menuBar.add(horizontalGlue);
		
		
		
		lblWelcome = new JLabel();
		lblWelcome.setForeground(new Color(0, 0, 128));
		menuBar.add(lblWelcome);
		
		horizontalStrut = Box.createHorizontalStrut(20);
		menuBar.add(horizontalStrut);
		
		mnProfile = new JMenu("Profile");
		menuBar.add(mnProfile);
		
		mntmUpdateCompany = new JMenuItem("Update Company");
		mntmUpdateCompany.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				CompanyUpdateCompany cuc = new CompanyUpdateCompany();
				cuc.setLocationRelativeTo(null);
				cuc.setVisible(true);
				cuc.setTitle("Company - Update Company Details");
				closeWindow();
			}
		});
		
		JMenuItem mntmViewCompany = new JMenuItem("View Company");
		mntmViewCompany.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				CompanyViewDetails cvd= new CompanyViewDetails();
				cvd.setLocationRelativeTo(null);
				cvd.setVisible(true);
				cvd.setTitle("Company - View Company Details");
				closeWindow();
			}
		});
		mnProfile.add(mntmViewCompany);
		
		JSeparator separator_3 = new JSeparator();
		mnProfile.add(separator_3);
		mnProfile.add(mntmUpdateCompany);
		
		
		menuExit = new JMenu("Exit");
		menuBar.add(menuExit);
		menuLogout=new JMenuItem("Logout");
		menuLogout.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				CompanyApp.logoutUser();
				
				CompanyLogin loginUI = new CompanyLogin();
				loginUI.setLocationRelativeTo(null);
				loginUI.setVisible(true);
				closeWindow();
			}
		});
		menuExit.add(menuLogout);
		if (CompanyApp.isUserLogin())
		{
			lblWelcome.setText("Welcome, " + CompanyApp.getCurrentUser().getCompanyName() + ".");
		}
		else
		{
			lblWelcome.setText("Welcome, Guest! Please Login.");
		}
		
		
		int count = cb_title.getItemCount() - 1;
		lblNewLabel.setText("Showing " +count + " job(s) posted by " + CompanyApp.getCurrentUser().getCompanyName() + ":" );
		
		JPanel panel = new JPanel();
		panel.setBackground(new Color(255, 255, 255));
		panel.setBounds(0, 22, 724, 500);
		getContentPane().add(panel);
		
		
		
		
		
	}

	public Object getSelectedItem() {
		return table.getValueAt(table.getSelectedRow(),
				table.getSelectedColumn());
	}

	public Object[] getSelectedItems() {
		ArrayList<Object> items = new ArrayList<Object>();
		for (int i : table.getSelectedRows()) {
			items.add(table.getValueAt(i, table.getSelectedColumn()));
		}
		return items.toArray();
	}

	
	/****HERE****/
	private class ViewPagination extends AbstractPagination {
		protected ViewPagination() {
			
			this.setCount(5);
			this.setTotal(jct.getTotalNumOfApplicantsOfJob());
		}

		@Override
		protected void action(Object[] data) {
			// clear all row
			tableModel.setRowCount(0);

			// add new row base on data size
			for (int i = 0; i < data.length; i++) {
				tableModel.addRow(new Object[] { data[i], data[i] });
			}
		}

		
		
		protected Object[] subData(int position, int count) {
			return jct.getMultipleApplicants(position, count).toArray();
		}
	}

	{

	}

	public void addProductListener(MouseListener productcellRenderer) {
		table.addMouseListener(productcellRenderer);
	}

	public Product getSelected() {
		return (Product) table.getModel().getValueAt(table.getSelectedRow(),
				table.getSelectedColumn());
	}
	
	
	public String getJobTitle(){
		return cb_title.getSelectedItem().toString();
	}
	
	public void closeWindow(){
		this.dispose();
	}
}
